package com.yzy.domain.strategy.service.rule.chain.factory;

import java.util.Map;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import com.yzy.domain.strategy.model.entity.StrategyEntity;
import com.yzy.domain.strategy.repository.IStrategyRepository;
import com.yzy.domain.strategy.service.rule.chain.ILogicChain;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * @author yangzhenyu05 <yangzhenyu05@kuaishou.com>
 * Created on 2024-01-22
 * @description 工厂
 */
@Service
public class DefaultChainFactory {
    private final Map<String, ILogicChain> logicChainGroup;
    protected IStrategyRepository repository;

    public DefaultChainFactory(Map<String, ILogicChain> logicChainGroup, IStrategyRepository strategyRepository) {
        this.repository = strategyRepository;
        this.logicChainGroup = logicChainGroup;
    }

    public ILogicChain openLogicChain(Long strategyId) {
        StrategyEntity strategy = repository.queryStrategyEntityByStrategyId(strategyId);
        String[] ruledModels = strategy.ruleModels();
        // 如果未配置策略规则，则只装配一个默认责任链
        if (ObjectUtils.isEmpty(ruledModels)) {
            return logicChainGroup.get(LogicModel.RULE_DEFAULT.getCode());
        }
        // 按照配置顺序装填用户配置的责任链；rule_blacklist、rule_weight 「注意此数据从Redis缓存中获取，如果更新库表，记得在测试阶段手动处理缓存」
        ILogicChain logicChain = logicChainGroup.get(ruledModels[0]);
        ILogicChain current = logicChain;
        for (int i = 1; i < ruledModels.length; i++) {
            ILogicChain nextChain = logicChainGroup.get(ruledModels[i]);
            current = current.appendNext(nextChain);
        }
        // 责任链的最后装填默认责任链
        current.appendNext(logicChainGroup.get(LogicModel.RULE_DEFAULT.getCode()));
        return logicChain;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class StrategyAwardVO {
        /**
         * 抽奖奖品ID - 内部流转使用
         */
        private Integer awardId;
        /**
         *
         */
        private String logicModel;
    }

    @Getter
    @AllArgsConstructor
    public enum LogicModel {

        RULE_DEFAULT("rule_default", "默认抽奖"),
        RULE_BLACKLIST("rule_blacklist", "黑名单抽奖"),
        RULE_WEIGHT("rule_weight", "权重规则"),
        ;

        private final String code;
        private final String info;

    }

}
